package cn.bellychang;

import cn.bellychang.mxbean.ControllerJmxReporter;
import cn.bellychang.mxbean.ControllerReporter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import javax.management.*;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * @author ChangLiang
 * @date 2020/2/21
 */
@SpringBootApplication
public class Bootstrap {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Bootstrap.class, args);
        ControllerJmxReporter controllerJmxReporter = (ControllerJmxReporter) context.getBean("controllerJmxReporter");
        registerMBean(controllerJmxReporter);
    }

    private static void registerMBean(ControllerJmxReporter controllerJmxReporter) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

            String domainName = "hfi-reporter";

            ObjectName objectName = new ObjectName(domainName + ":name=deferredresult");
            ControllerReporter controllerReporter = new ControllerReporter();
            controllerReporter.setData(controllerJmxReporter.collect());
            mbs.registerMBean(controllerReporter, objectName);

            int rmiPort = 1099;
            Registry registry = LocateRegistry.createRegistry(rmiPort);

            JMXServiceURL url =
                    new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + rmiPort + "/" + domainName);
            JMXConnectorServer jmxConnector = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
            jmxConnector.start();
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        } catch (InstanceAlreadyExistsException e) {
            e.printStackTrace();
        } catch (MBeanRegistrationException e) {
            e.printStackTrace();
        } catch (NotCompliantMBeanException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
